<!--
 * @desc:
 * @Author: 钟强
 * @Date: 2021-12-24 10:06:30
 * @LastEditors: 钟强
 * @LastEditTime: 2021-12-24 11:41:29
-->
<template>
  <div class="markdown-container">
    <!-- 渲染区 -->
    <div id="markdown-box"></div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">
        {{
          $t('msg.article.commit')
        }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
// Editor实例
import MkEditor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn'
import { onMounted, defineProps, defineEmits, watch } from 'vue'
import { watchSwitchLang } from '@/utils/i18n'
import { useStore } from 'vuex'
import { commitArticle } from './components/commit'

const props = defineProps({
  title: {
    require: true,
    type: String
  },
  detail: {
    type: Object
  }
})
const emits = defineEmits(['onSuccess'])
let mkEditor
// 处理离开页面切换语言导致 dom 无法被获取
let el
// 处理提交
const onSubmitClick = async () => {
  // 创建文章
  await commitArticle({
    title: props.title,
    content: mkEditor.getHTML()
  })

  mkEditor.reset()
  emits('onSuccess')
}
onMounted(() => {
  el = document.querySelector('#markdown-box')
  initEditor()
})

const store = useStore()
const initEditor = () => {
  mkEditor = new MkEditor({
    el,
    height: '500px',
    previewStyle: 'vertical',
    language: store.getters.language === 'zh' ? 'zh-CN' : 'en'
  })

  mkEditor.getMarkdown()
}

watchSwitchLang(() => {
  if (!el) return
  const htmlStr = mkEditor.getHTML()
  mkEditor.destroy()
  initEditor()
  mkEditor.setHTML(htmlStr)
})

// 监听详情的变化很小的
watch(() => props.detail, (val) => {
  if (val && val.content) {
    mkEditor.setHTML(val.content)
  }
}, {
  immediate: true
})

</script>

<style lang="scss" scoped>
.markdown-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
